package com.shiwaixiangcun.customer.module.homeservice

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.ImageDisplayUtil
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.activity.LoginActivity
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.ArithmeticUtils
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.utils.LoginHelper
import kotlinx.android.synthetic.main.activity_service_detail.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class ServiceDetailActivity : BaseActivity(), View.OnClickListener {
    companion object {
        val REQUEST_DATA = 1
    }

    private var detailUrl: String? = null
    private var tokenString: String? = null
    private var serviceID: Long? = null
    private var serviceName: String? = null
    private var servicePic: String? = null
    private var serviceDesc: String? = null
    private var servicePrice: String? = null
    private var strToken: String? = null
    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
            R.id.btn_appointment -> {
                if (LoginHelper.isLogin(mContext)) {
                    val bundle = Bundle()
                    serviceID?.let { bundle.putLong("id", it) }
                    bundle.putString("name", serviceName)
                    bundle.putString("pic", servicePic)
                    bundle.putString("desc", serviceDesc)
                    bundle.putString("price", servicePrice)
                    readyGo(AppointmentActivity::class.java, bundle)

                } else {
                    readyGo(LoginActivity::class.java)
                }


            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service_detail)
        EventUtil.getInstance().register(this)

        initBundleData()
        initViewAndEvent()
        initData()
    }


    /**
     * 获取数据
     */
    private fun initData() {
        strToken = AppSharePreferenceMgr.get(this, ConfigSps.CURRENT_TOKEN, "") as String
        serviceID?.let {
            OkGo.get<String>(GlobalApi.serviceDetail)
                    .params("id", it)
                    .execute(object : StringCallback() {
                        override fun onSuccess(response: Response<String>?) {
                            val type = object : TypeToken<CommonObjCallBack<ServiceDetail>>() {}.type
                            val responseData = JsonUtil.fromJson<CommonObjCallBack<ServiceDetail>>(response?.body(), type)
                            when (responseData.responseCode) {
                                ResponseConfig.SUCCESS -> {

                                    EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOME_SERVICE_DETAIL, REQUEST_DATA, responseData.data))
                                }

                            }

                        }

                    })
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updaterUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.HOME_SERVICE_DETAIL) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_DATA -> {
                val serviceDetail = simpleEvent.data as ServiceDetail

                //赋值
                serviceName = serviceDetail.serviceName
                serviceDesc = serviceDetail.feature
                servicePic = serviceDetail.image[0].thumbImage
                servicePrice = ArithmeticUtils.format(serviceDetail.price)

                //更新界面
                tv_house_title.text = serviceDetail.serviceName
                tv_house_desc.text = serviceDetail.feature
                ImageDisplayUtil.showImageView(mContext, serviceDetail.image[0].thumbImage, iv_house_cover)
                if ("0.00" == servicePrice) {
                    tv_price.text = "暂不收费"

                    tv_price.textSize = 14.0f
                } else {
                    tv_price.text = servicePrice
                    tv_unit.visibility = View.VISIBLE
                    tv_price_flag.visibility = View.VISIBLE
                }
                detailUrl = "${GlobalApi.DOMAIN_MK}/mi/toHomeService/detail/view.htm?id=$serviceID"
                webView.loadUrl(detailUrl)
            }
        }

    }

    private fun initBundleData() {
        serviceID = intent.extras.getLong("serviceId")
    }

    /**
     *初始化视图和点击事件
     */
    private fun initViewAndEvent() {
        tv_page_name.text = resources.getText(R.string.service_detail)
        back_left.setOnClickListener(this)
        btn_appointment.setOnClickListener(this)
    }



    override fun onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webView.clearHistory()

            (webView.parent as ViewGroup).removeView(webView)
            webView.destroy()

        }
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }


}
